package 文件上传03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class 服务端 {
    public static void main(String[] args)throws Exception {
        ServerSocket serverSocket = new ServerSocket(6666);
        ExecutorService executorService = Executors.newFixedThreadPool(10);


        while (true) {
            Socket socket = serverSocket.accept();

            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(socket.getInetAddress().getHostAddress()+"开始上传");
                        /*3.创建输入流，指向客户端*/
                        InputStream is = socket.getInputStream();

                        /*4.创建输出流，指向文件*/
                        FileOutputStream fos = new FileOutputStream("socket/"+ UUID.randomUUID());

                        byte[] data = new byte[1024];
                        int len;
                        while((len=is.read(data)) != -1){
                            fos.write(data,0,len);
                        }

                        System.out.println(socket.getInetAddress().getHostAddress()+"上传完毕");
                        /*5.创建输出流，写"上传成功" 给客户端*/
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        writer.write("上传成功");
                        writer.newLine();
                        writer.flush();

                        fos.close();
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }


    }
}
